package com.xxg.fileshand.activity

import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.ToastUtils
import com.rscja.deviceapi.entity.UHFTAGInfo
import com.xxg.fileshand.R
import com.xxg.fileshand.app.App
import com.xxg.fileshand.app.SetInfo
import com.xxg.fileshand.base.BaseVMActivity
import com.xxg.fileshand.base.NoViewModel
import com.xxg.fileshand.base.ext.dataConvert
import com.xxg.fileshand.base.ext.getApiService
import com.xxg.fileshand.base.launch
import com.xxg.fileshand.bean.RequestTagBean
import com.xxg.fileshand.constant.Constant
import com.xxg.fileshand.databinding.ActivityFilesFindBinding
import com.xxg.fileshand.greendao.GreenDaoManager
import com.xxg.fileshand.reader.ReaderUtils
import com.xxg.fileshand.type.OperateType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.util.UUID

class FilesFindActivity : BaseVMActivity<ActivityFilesFindBinding, NoViewModel>() {

    var page = 1
    var pageSize = 10

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ReaderUtils.instance.playSoundFlag = false

        initFilesAdapter()
        initLoad()


        showRightText("清除")
        filesAdapter.setEmptyView(R.layout.search_empty)
        filesAdapter.isFind = true
        filesAdapter.addChildClickViewIds(R.id.bt_find)
        initAdapterClick(mBinding.tvHint)
        filesAdapter.setOperateType(OperateType.OPERATE_TYPE_SEARCH)

        mBinding.etInput.setOnEditorActionListener { textView, i, keyEvent ->
            //搜索键匹配
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                ReaderUtils.instance.needReadTid = null
                filesList.clear()
                filesAdapter.notifyDataSetChanged()
                mBinding.tvHint.visibility = View.GONE
                ReaderUtils.instance.reset()
                page = 1
                toast("正在查询")
                searchWz()
            }

            return@setOnEditorActionListener true
        }

    }

    private fun initLoad() {
        if (!SetInfo.isOffline()) {
            filesAdapter.loadMoreModule.setOnLoadMoreListener {
//                if (!SetInfo.isOffline()) {
                    page++
                    searchWz()
//                }
            }
        }

    }

    private fun searchWz() {
        if (SetInfo.isOffline()) {
            if (mBinding.rbId.isChecked) {
                val wzRp =
                    GreenDaoManager.findFilesInfoDTOByDaCode(mBinding.etInput.text.toString())
                wzRp?.let {
                    filesList.addAll(it)
                    filesAdapter.notifyDataSetChanged()
//                    ReaderUtils.instance.needReadTid = it.eid
                    hideSoftKeyboard()
                } ?: toast("未找到档案")
            } else {
                val wzRp = GreenDaoManager.findFilesInfoDTOByName(mBinding.etInput.text.toString())
                wzRp?.let {
                    filesList.addAll(it)
                    filesAdapter.notifyDataSetChanged()
//                    ReaderUtils.instance.needReadTid = it.eid
                    hideSoftKeyboard()
                } ?: toast("未找到档案")
            }
        } else {
            hideSoftKeyboard()
            launch({
                var isId = mBinding.rbId.isChecked
                val wzRp = getApiService().findArchive(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        if (isId) {
                            "daCode" to mBinding.etInput.text.toString()
                        } else {
                            "daName" to mBinding.etInput.text.toString()
                        },
                        "pageNum" to page,
                        "pageSize" to pageSize
                    )
                )
                if (wzRp.code == Constant.Code.OK) {
                    if (wzRp.rows == null || wzRp.rows!!.isEmpty()) {
                        toast("未找到档案")
                        filesAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        filesList.addAll(wzRp.rows!!)
                        filesAdapter.notifyDataSetChanged()
                        if (filesList.size >= wzRp.total) {
                            filesAdapter.loadMoreModule.loadMoreEnd()
                        } else {
                            filesAdapter.loadMoreModule.loadMoreComplete()
                        }
                    }
                } else {
                    if (wzRp.code == Constant.Code.UnAuthorized) {
                        ReaderUtils.instance.release()
                        ToastUtils.showShort("登录过期，请重新登录")
                        App.token = ""
                        Handler().postDelayed({
                            AppUtils.relaunchApp(true)
                        }, 1000)
                    } else {
                        toast(wzRp.msg)
                    }
                }
            }, {
                toast(it.message)
            })
        }
    }

    override fun getMyTitle(): String {
        return "档案查询"
    }

    override fun onLeftClick() {
        onBackPressed()
    }

    override fun onRightClick() {
        ReaderUtils.instance.needReadTid = null
        filesList.clear()
        filesAdapter.notifyDataSetChanged()
        mBinding.tvHint.visibility = View.GONE
        ReaderUtils.instance.reset()
        mBinding.etInput.setText("")
    }

    override fun onBackPressed() {
        ReaderUtils.instance.needReadTid = null
        if (filesList.size > 0) {
            mBinding.etInput.setText("")
            filesList.clear()
            filesAdapter.notifyDataSetChanged()
            mBinding.tvHint.visibility = View.GONE
            ReaderUtils.instance.reset()
        } else {
            ReaderUtils.instance.playSoundFlag = true
            super.onBackPressed()
        }
    }

    override fun isScan(): Boolean {
        return true
    }

    override fun onEpcRead(tagInfo: UHFTAGInfo) {
        if (filesList.size > 0 && ReaderUtils.instance.needReadTid == tagInfo.tid) {
            ReaderUtils.instance.playAudio()
            mBinding.tvHint.visibility = View.VISIBLE
            ReaderUtils.instance.stopScan()
            launch({
                //子线程执行 避免阻塞
                withContext(Dispatchers.IO) {
                    ReaderUtils.instance.readData(tagInfo.tid)
                }
                if (ReaderUtils.instance.isScanningRFID.value == false) {
                    delay(30)
                    ReaderUtils.instance.startScan()
                }
            })
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (!isFinishing && ReaderUtils.instance.isScanBtn(keyCode) && filesList.isEmpty()) {
            toast("请先查询档案信息")
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

}